<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-button v-if="checkPermission('添加角色')"  style="margin-left:20px" class="filter-item" type="primary" icon="el-icon-plus" @click="createRole">
              新增角色
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :data="list"
              ref="equipTable"
              border
              fit
              stripe
              highlight-current-row
              :row-style="{height:40+'px'}"
              :cell-style="{padding:0+'px'}"
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column label="角色" align="left" width="180">
                <template slot-scope="{row}">
                  <span>{{row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column label="描述" align="left" >
                <template slot-scope="{row}">
                  <span>{{row.description}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                <template v-slot="{row,$index}">
                  <el-button v-if="checkPermission('修改角色')" type="primary" icon="el-icon-edit" circle  @click="updateRole(row)">
                  </el-button>
                  <el-button v-if="checkPermission('删除角色')" icon="el-icon-delete" type="danger" circle @click="handleDelete(row,$index)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" custom-class="window-small-width">
              <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px" >
                <el-form-item label="角色名" prop="name" >
                  <el-input :disabled="dialogStatus == 'update'" v-model="temp.name" />
                </el-form-item>
                <el-form-item label="描述" prop="remark" label-width="80px">
                  <el-input v-model="temp.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="菜单">
                  <el-tree
                    ref="tree"
                    :check-strictly="checkStrictly"
                    :row-style="{height:0+'px'}"
                    :cell-style="{padding:0+'px'}"
                    :data="routers"
                    :props="defaultProps"
                    show-checkbox
                    node-key="path"
                    class="permission-tree"
                  />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button  type="primary" @click="dialogStatus == 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {getRoles,addRole,deleteRole,updateRole,getRoutes} from "@/api/role";
import path from "path";
import {deepClone} from "@/utils";
import {checkPermission} from "@/utils/permission";

const defaultRole = {
  name:'',
  description:'',
  routers:[],
}

export default {
  name: 'roles',
  data() {
    return {
      tableKey:0,
      listLoading:true,
      list:[],
      routers: [],
      rawRouters : [],
      temp:'',
      textMap: {
        update: '编辑角色',
        create: '新建角色'
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      checkStrictly: false,
      dialogFormVisible:false,
      dialogStatus:'create',
      checkedKeys:[],
      rules: {
        name: [{ message:'角色名必填',required: true, trigger: 'blur' }]
      },
    }
  },
  created() {
    this.resetTemp()
    this.getRoles()
    this.routerList()
  },
  computed:{
    routesData() {
      return this.routes
    }
  },
  methods: {
    checkPermission,
    async routerList(){
      getRoutes().then(res => {
        this.rawRouters = Object.assign([],res.data)
        this.routers = this.generateRoutes(res.data)
      })
    },
    generateRoutes(routes, basePath = '/') {
      const res = []
      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }
        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }
        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title,
        }

        if(route.meta && route.meta.actions){
          data.children = this.generateActions(route.meta.actions)
        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateActions(actions){
      let r = []
      for (let i in actions){
        r.push({path:actions[i],title: actions[i]})
      }
      return r
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)
        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

      let actions = []
        if(route.meta && route.meta.actions){
          for (let i in route.meta.actions){
            if(checkedKeys.includes(route.meta.actions[i])){
              actions.push(route.meta.actions[i])
            }
          }
        }
        if(route.meta && route.meta.actions){
          route.meta.actions = actions
        }
        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1) || (route.meta && route.meta.actions && route.meta.actions.length >=1)) {
          res.push(route)
        }


      }
      return res
    },
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },
    getRoles(){
      this.listLoading = true
      getRoles({}).then(response => {
        this.list = response.data.list
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    createRole(){
      this.resetTemp()
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleCreate(){
      let tempData = Object.assign({},this.temp)
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      tempData.routers = this.generateTree(deepClone(this.rawRouters), '/', checkedKeys)
      tempData.routers = JSON.stringify(tempData.routers)
      addRole(tempData).then(response => {
        if (response.code == 20000) {
          this.$notify({
            title: 'Success',
            message: '操作成功',
            type: 'success',
            duration: 3000
          })
          this.getRoles()
        } else {
          this.$notify({
            title: 'Failed',
            message: response.message,
            type: 'error',
            duration: 3000
          })
        }
      })
      this.dialogFormVisible = false
    },
    getKeys(nodes){
      for (const node of nodes){
        if(node.children){
          this.getKeys(node.children)
        }else{
          this.checkedKeys.push(node.path)
        }
      }
    },
    updateRole(row){
      this.checkedKeys = []
      this.temp = Object.assign({},row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.temp = deepClone(row)
      this.temp.routers = this.generateRoutes(JSON.parse(this.temp.routers))
      this.getKeys(this.temp.routers)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs.tree.setCheckedKeys(this.checkedKeys)
      })
    },
    handleUpdate(){
      let tempData = Object.assign({},this.temp)
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      tempData.routers = this.generateTree(deepClone(this.rawRouters), '/', checkedKeys)
      tempData.routers = JSON.stringify(tempData.routers)
      updateRole(tempData).then(response => {
        if (response.code == 20000) {
          this.$notify({
            title: 'Success',
            message: '操作成功',
            type: 'success',
            duration: 3000
          })
          this.getRoles()
        } else {
          this.$notify({
            title: 'Failed',
            message: response.message,
            type: 'error',
            duration: 3000
          })
        }
      })
      this.dialogFormVisible = false
    },
    handleDelete(row,index){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({id:row.id}).then(response => {
          if (response.code == 20000) {
            this.$notify({
              title: 'Success',
              message: '成功删除',
              type: 'success',
              duration: 3000
            })
            this.getRoles()
          } else {
            this.$notify({
              title: 'Failed',
              message: '无法删除',
              type: 'error',
              duration: 3000
            })
          }
        })
      }).catch(err =>{})
    },
    resetTemp(){
      this.temp = Object.assign({},defaultRole)
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
